﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using WebApplication1.Libs;

namespace WebApplication1.Lists
{
    public class DoiTuong
    {
        #region ID property
        public Guid ID
        {
            get
            {
                if (_DataRow["ID"] is Guid)
                    return (Guid)_DataRow["ID"];
                else
                    return Guid.Empty;
            }
            set
            {
                _DataRow["ID"] = value;
            }
        }
        #endregion

        #region Disable property
        public bool Disable
        {
            get
            {
                if (_DataRow["Disable"] is bool)
                    return (bool)_DataRow["Disable"];
                else
                    return false;
            }
            set
            {
                _DataRow["Disable"] = value;
            }
        }
        #endregion

        protected DataRow _DataRow = null;
        public DataRow DataRow
        {
            get
            {
                return _DataRow;
            }
            set
            {
                _DataRow = value;
            }
        }

        public virtual void InsertToDB()
        {

            SqlConnection con = new SqlConnection(Connection._ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                InsertToDB(cmd);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                con.Close();
            }
        }
        public virtual void UpdateToDB()
        {
            SqlConnection con = new SqlConnection(Connection._ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                UpdateToDB(cmd);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                con.Close();
            }
        }

        public virtual void InsertToDB(SqlCommand cmd)
        {
            if (cmd.Connection.State != ConnectionState.Open) throw new Exception("Chưa mở connection");
            string values = ""; string listOfColumns = "";
            cmd.Parameters.Clear();
            foreach (DataColumn column in this.DataRow.Table.Columns)
            {
                if (column.ColumnName != "LastUpdated")
                {
                    values = values + "@" + column.ColumnName + ", ";
                    listOfColumns = listOfColumns + column.ColumnName + ", ";
                    cmd.Parameters.AddWithValue(column.ColumnName, this.DataRow[column.ColumnName]);
                }
            }

            if (values.EndsWith(", ")) values = values.Substring(0, values.Length - 2);
            if (listOfColumns.EndsWith(", ")) listOfColumns = listOfColumns.Substring(0, listOfColumns.Length - 2);

            cmd.CommandText = string.Format("INSERT INTO [{0}]({1}) VALUES({2})",
                                                this.DataRow.Table.TableName, listOfColumns, values);
            cmd.ExecuteNonQuery();
            if (this.DataRow.Table.Rows.IndexOf(this.DataRow) < 0) this.DataRow.Table.Rows.Add(this.DataRow);
        }
        public virtual void UpdateToDB(SqlCommand cmd)
        {
            if (cmd.Connection.State != ConnectionState.Open) throw new Exception("Chưa mở connection");
            string values = "";
            cmd.Parameters.Clear();
            foreach (DataColumn column in this.DataRow.Table.Columns)
            {
                if (column.ColumnName != "LastUpdated" && column.ColumnName != this.DataRow.Table.TableName + "ID")
                {
                    values += string.Format("{0} = @{0}, ", column.ColumnName);
                    if (this.DataRow[column.ColumnName] is Guid && (Guid)this.DataRow[column.ColumnName] == Guid.Empty)
                    {
                        cmd.Parameters.AddWithValue(column.ColumnName, DBNull.Value);
                    }
                    else
                    {
                        cmd.Parameters.AddWithValue(column.ColumnName, this.DataRow[column.ColumnName]);
                    }
                }
            }

            if (values.EndsWith(", ")) values = values.Substring(0, values.Length - 2);

            cmd.CommandText = string.Format("UPDATE [{0}] SET {1} WHERE ID = '{2}'",
                                                this.DataRow.Table.TableName,
                                                values,
                                                this.DataRow["ID"]);
            cmd.ExecuteNonQuery();
        }

        public virtual void DeleteFromDB()
        {
            SqlConnection con = new SqlConnection(Connection._ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = string.Format("DELETE FROM [{0}] WHERE ID = '{1}'",
                                                    this.DataRow.Table.TableName,
                                                    this.DataRow["ID"]);
                cmd.ExecuteNonQuery();
                _DataRow.Delete();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                con.Close();
            }
        }
        public virtual void DeleteFromDB(SqlCommand cmd)
        {
            try
            {
                cmd.CommandText = string.Format("DELETE FROM [{0}] WHERE ID = '{1}'",
                                                    this.DataRow.Table.TableName,
                                                    this.DataRow["ID"]);
                cmd.ExecuteNonQuery();
                _DataRow.Delete();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                cmd.Connection.Close();
            }
        }

        public DoiTuong()
        {
            //_DataRow = dataRow;
            //if (this.ID == Guid.Empty) this.ID = CustomGuid.NewSequentialId();
        }
        public DoiTuong(DataRow dataRow)
        {
            _DataRow = dataRow;
            if (this.ID == Guid.Empty) this.ID = Guid.NewGuid();
        }
    }

    public abstract class DanhMucDoiTuong
    {
        #region TableName property
        public virtual string TableName
        {
            get
            {
                throw new Exception("Chưa khởi tạo tên bảng cho danh mục. Lỗi lập trình: cần overide TableName");
            }
        }
        #endregion

        #region DataTable property
        public DataSet _DataSet;
        public DataTable DataTable
        {
            get
            {
                if (_DataSet == null || _DataSet.Tables.Count == 0)
                {
                    _DataSet = new DataSet();
                    LoadFromDB();
                }
                return _DataSet.Tables[0];
            }
        }
        #endregion

        #region DataView property
        private DataView _DataView;
        public DataView DataView
        {
            get
            {
                return _DataView;
            }
            set
            {
                _DataView = value;
            }
        }
        #endregion

        public delegate void ChangeHandler();
        public event ChangeHandler Change;
        protected SqlDataAdapter _DataAdapter = new SqlDataAdapter();

        protected DanhMucDoiTuong()
        {
        }

        public void LoadFromDB()
        {
            SqlConnection con = new SqlConnection(Connection._ConnectString);
            try
            {
                SqlCommand cmd = con.CreateCommand();

                switch (TableName)
                {
                    case "VatTuHangHoa":
                        cmd.CommandText = string.Format("SELECT * FROM {0} ORDER BY Ten", TableName);
                        break;
                    case "DoiTuongNghiepVu":
                        cmd.CommandText = string.Format("SELECT * FROM {0} ORDER BY Ten", TableName);
                        break;
                    case "TaiKhoan":
                        cmd.CommandText = string.Format("SELECT * FROM {0} ORDER BY SoHieu", TableName);
                        break;
                    case "Kho":
                        cmd.CommandText = string.Format("SELECT * FROM [{0}] ORDER BY STT ", TableName);
                        break;
                    case "ChiTietKhuyenMaiTheoThoiGian":
                        cmd.CommandText = string.Format("SELECT * FROM {0} ORDER BY ChuongTrinhKhuyenMaiID", TableName);
                        break;
                    case "ChuongTrinhKhuyenMai":
                        cmd.CommandText = string.Format("SELECT * FROM {0} ORDER BY ID", TableName);
                        break;
                    case "DoiTuongKhuyenMai":
                        cmd.CommandText = string.Format("SELECT * FROM {0} ORDER BY ChuongTrinhKhuyenMaiID", TableName);
                        break;
                    case "Function":
                        cmd.CommandText = string.Format("SELECT * FROM [{0}] ORDER BY ParentFunctionID", TableName);
                        break;
                    default:
                        cmd.CommandText = string.Format("SELECT * FROM {0}", TableName);
                        break;
                }

                _DataAdapter.SelectCommand = cmd;
                _DataSet.Clear();
                _DataAdapter.Fill(_DataSet, TableName);
            }
            catch (SqlException sqlEx)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
            }
        }

        public void InsertToDB(DoiTuong doiTuong)
        {
            if (DataTable.Rows.IndexOf(doiTuong.DataRow) < 0) DataTable.Rows.Add(doiTuong.DataRow);
        }

        public void UpdateToDB()
        {
            try
            {
                SqlCommandBuilder commandBuilder = new SqlCommandBuilder((SqlDataAdapter)_DataAdapter);
                commandBuilder.DataAdapter.Update(_DataSet, TableName);
                this.DataTable.AcceptChanges();
                try
                {
                    if (Change != null) Change();
                }
                catch (Exception ex)
                {
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public int Count
        {
            get
            {
                return this.DataView.Count;
            }
        }
        protected DataRow[] GetDataRows(string filterExpression)
        {
            try
            {
                return DataTable.Select(filterExpression);
            }
            catch (Exception ex)
            {

                return null;
            }
        }

        protected DataRow[] GetDataRows(string property, object value)
        {
            try
            {
                string filterExpression = "";
                if (value is string)
                {
                    value = (value as string).Replace("'", "''");
                    filterExpression = string.Format("{0} = '{1}'", property, value);
                }
                else if (value is Guid)
                    filterExpression = string.Format("{0} = '{1}'", property, value);
                else
                    filterExpression = string.Format("{0} = {1}", property, value);

                return DataTable.Select(filterExpression);
            }
            catch (Exception ex)
            {

                return null;
            }
        }

        public static void LoadFromDBForCheckExisted(string tableName)
        {
            SqlConnection con = new SqlConnection(Connection._ConnectString);
            try
            {
                SqlCommand cmd = con.CreateCommand();

                switch (tableName)
                {
                    case "VatTuHangHoa":
                        cmd.CommandText = string.Format("SELECT TOP 1 * FROM {0} ORDER BY Ten", tableName);
                        break;
                    case "DoiTuongNghiepVu":
                        cmd.CommandText = string.Format("SELECT TOP 1 * FROM {0} ORDER BY Ten", tableName);
                        break;
                    case "TaiKhoan":
                        cmd.CommandText = string.Format("SELECT TOP 1 * FROM {0} ORDER BY SoHieu", tableName);
                        break;
                    case "Kho":
                        cmd.CommandText = string.Format("SELECT TOP 1 * FROM [{0}] ", tableName);
                        break;
                    case "ChiTietKhuyenMaiTheoThoiGian":
                        cmd.CommandText = string.Format("SELECT TOP 1 * FROM {0} ORDER BY ChuongTrinhKhuyenMaiID", tableName);
                        break;
                    case "ChuongTrinhKhuyenMai":
                        cmd.CommandText = string.Format("SELECT TOP 1 * FROM {0} ORDER BY ID", tableName);
                        break;
                    case "DoiTuongKhuyenMai":
                        cmd.CommandText = string.Format("SELECT TOP 1 * FROM {0} ORDER BY ChuongTrinhKhuyenMaiID", tableName);
                        break;
                    case "Function":
                        cmd.CommandText = string.Format("SELECT TOP 1 * FROM [{0}] ORDER BY ParentFunctionID", tableName);
                        break;
                    default:
                        cmd.CommandText = string.Format("SELECT TOP 1 * FROM [{0}]", tableName);
                        break;
                }

                SqlDataAdapter da = new SqlDataAdapter();
                DataTable dt = new DataTable();
                da.Fill(dt);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
            }
        }

        public static bool CheckExistedTableInDB(string tableName)
        {
            try
            {
                LoadFromDBForCheckExisted(tableName);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}
